/***************************************************************
 * Name:      googlecalendarclientMain.cpp
 * Purpose:   Code for Application Frame
 * Author:    Daniel King (cnkknd@gmail.com)
 * Created:   2007-04-22
 * Copyright: Daniel King ()
 * License:
 **************************************************************/

#include "wx_pch.h"

#ifdef __BORLANDC__
#pragma hdrstop
#endif //__BORLANDC__

#include "loginForm.h"
#include "resource.h"
#include "crypt.h"

BEGIN_EVENT_TABLE(LoginForm, wxDialog)
	EVT_CLOSE(LoginForm::OnClose)
	EVT_MENU(idMenuQuit, LoginForm::OnQuit)
	EVT_MENU(idMenuAbout, LoginForm::OnAbout)
	EVT_BUTTON(idLoginButton, LoginForm::OnLogin)
	EVT_INIT_DIALOG(LoginForm::OnCreate)
	EVT_TIMER(idTimer, LoginForm::OnTimer)
	EVT_BUTTON(idConnectImmediately, LoginForm::OnConnectImmediately)
	EVT_BUTTON(idStopConnecting, LoginForm::OnStopConnecting)
END_EVENT_TABLE()

LoginForm::LoginForm(const wxString& title)
        : wxDialog((wxDialog*)NULL, -1, title, wxDefaultPosition, wxSize(400, 240),
        0
        | wxMINIMIZE_BOX
        | wxSYSTEM_MENU
        | wxCAPTION
        | wxCLOSE_BOX
        //| wxCLIP_CHILDREN
        )
{
    this->Center();
    wxImage::AddHandler(new wxJPEGHandler);
    InitXmlResource();

    this->SetBackgroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_BTNFACE ) );
    this->SetSizeHints( wxSize( 406,240 ), wxSize( 1024, 768 ) );

    wxXmlResource::Get()->InitAllHandlers();
    wxBitmap background = wxXmlResource::Get()->LoadBitmap(_T("splash"));
    wxStaticBitmap *staticBitmap = new wxStaticBitmap(this, wxID_ANY, background, wxPoint(0, 0), wxSize(400, 90));

    sizerLogin = new wxFlexGridSizer(5,1,0,0);
    sizerLogin->AddGrowableCol(0);
    sizerLogin->AddGrowableRow(2);
    sizerLogin->AddGrowableRow(3);
    sizerLogin->SetFlexibleDirection( wxBOTH );

    wxFlexGridSizer* sizerLoginInput = new wxFlexGridSizer(2,2,0,0);
    m_pEditLoginAccount = new wxTextCtrl(this, wxID_ANY, _("Your Google Account"), wxDefaultPosition, wxSize(180, 20));
    m_pEditLoginPasswd = new wxTextCtrl(this, wxID_ANY, _T(""), wxDefaultPosition, wxSize(180, 20), wxTE_PASSWORD);

    sizerLoginInput->Add(new wxStaticText(this, wxID_ANY, _("Account")), 0, wxALL, 3);
    sizerLoginInput->Add(m_pEditLoginAccount, 0, wxALL, 3);
    sizerLoginInput->Add(new wxStaticText(this, wxID_ANY, _("Password")), 0, wxALL, 3);
    sizerLoginInput->Add(m_pEditLoginPasswd, 0, wxALL, 3);

    sizerLoginMain = new wxBoxSizer(wxHORIZONTAL);
    sizerLoginMain->Add(sizerLoginInput, 0, wxALL, 2);
    sizerLoginMain->Add(new wxButton(this, idLoginButton, _("Login"), wxDefaultPosition, wxSize(50, 50)), 0, wxALL, 3);

    sizerLoginProcess = new wxBoxSizer(wxVERTICAL);

    wxBoxSizer *sizerLoginCountdown = new wxBoxSizer(wxHORIZONTAL);
    m_pStaictCountdown = new wxStaticText(this, wxID_ANY, _T("10"));
    sizerLoginCountdown->Add(new wxStaticText(this, wxID_ANY, _("Connecting to Google Calendar...")), 0, wxALIGN_CENTER, 10);
    sizerLoginCountdown->Add(10, 0, 1, wxEXPAND, 5);
    sizerLoginCountdown->Add(m_pStaictCountdown, 0, wxALIGN_CENTER, 10);

    sizerLoginProcess->Add(sizerLoginCountdown, 0, wxALIGN_CENTER, 10);
    sizerLoginProcess->Add(0, 5, 1, wxEXPAND, 5);
    sizerLoginProcess->Add(new wxButton(this, idConnectImmediately, _("Connect immediately")), 0, wxALIGN_CENTER, 4);
    sizerLoginProcess->Add(0, 2, 1, wxEXPAND, 5);
    sizerLoginProcess->Add(new wxButton(this, idStopConnecting, _("Stop connecting")), 0, wxALIGN_CENTER, 4);

    sizerLoginOpt = new wxBoxSizer(wxHORIZONTAL);
    m_pCbLoginOptRemAccount = new wxCheckBox(this, wxID_ANY, _("Remember Account"));
    m_pCbLoginOptRemPasswd = new wxCheckBox(this, wxID_ANY, _("Remember Password"));
    m_pCbLoginOptAutoLogin = new wxCheckBox(this, wxID_ANY, _("Auto Login"));
    sizerLoginOpt->Add(m_pCbLoginOptRemAccount, 0, wxALL, 5);
    sizerLoginOpt->Add(m_pCbLoginOptRemPasswd, 0, wxALL, 5);
    sizerLoginOpt->Add(m_pCbLoginOptAutoLogin, 0, wxALL, 5);

    wxBoxSizer* sizerLoginOther = new wxBoxSizer(wxHORIZONTAL);
    //sizerLoginOther->Add(new wxHyperlinkCtrl(this, wxID_ANY, _("Connection Settings"), _T("")), 0, wxALL, 7);
    sizerLoginOther->Add( 0, 0, 1, wxEXPAND, 5 );
    sizerLoginOther->Add(new wxHyperlinkCtrl(this, wxID_ANY, _("Visit Google"), _T("http://www.google.com/")), 0, wxALL, 7);
    sizerLoginOther->Add(new wxHyperlinkCtrl(this, wxID_ANY, _("Visit Google Calendar"), _T("http://www.google.com/calendar")), 0, wxALL, 7);

    sizerLogin->Add(staticBitmap, 1, wxALIGN_BOTTOM|wxALIGN_CENTER_HORIZONTAL, 5);
	sizerLogin->Add( 0, 15, 1, wxEXPAND, 5 );
    sizerLogin->Add(sizerLoginMain, 1, wxALIGN_CENTER, 5);
    sizerLogin->Add(sizerLoginProcess, 1, wxALIGN_CENTER, 5);
    sizerLogin->Add(sizerLoginOpt, 1, wxALIGN_TOP|wxALIGN_CENTER_HORIZONTAL, 5);

    sizerLogin->Show(sizerLoginProcess, false);

    sizerLogin->Add(sizerLoginOther, 1,  wxEXPAND, 5);
    SetSizer(sizerLogin);
    Layout();

	m_pEditLoginAccount->Connect(wxEVT_ENTER_WINDOW, wxMouseEventHandler(LoginForm::OnEditMouseEnter));
	m_pEditLoginPasswd->Connect(wxEVT_ENTER_WINDOW, wxMouseEventHandler(LoginForm::OnEditMouseEnter));

    m_pTimer = new wxTimer(this, idTimer);
    m_bLoginImmediately = false;
}

LoginForm::~LoginForm()
{}

void LoginForm::OnCreate(wxInitDialogEvent &event)
{
    wxFileConfig *config = new wxFileConfig(_T("GoogleCalendarClient"), _T(""), wxGetCwd() + _T("/config.dat"), _T(""), wxCONFIG_USE_LOCAL_FILE);
    wxConfigBase::Set(config);

    wxString s;
    bool b;
	m_bEncodedPasswd = false;
	m_sEncodedPasswd.Clear();
    if(config->Read(_T("/login/rememberaccount"), &b))
    {
        m_pCbLoginOptRemAccount->SetValue(b);
        if(b && config->Read(_T("/login/account"), &s)) m_pEditLoginAccount->SetValue(s);
    }
    if(config->Read(_T("/login/rememberpassword"), &b))
    {
        m_pCbLoginOptRemPasswd->SetValue(b);
        if(b && config->Read(_T("/login/password"), &s))
		{
			m_sEncodedPasswd = s;
			m_pEditLoginPasswd->SetValue(s);
			m_bEncodedPasswd = true;
		}
    }
    if(config->Read(_T("/login/autologin"), &m_bAutoLogin))
    {
        m_pCbLoginOptAutoLogin->SetValue(m_bAutoLogin);
        if(m_bAutoLogin) Login();
    }
}

void LoginForm::OnClose(wxCloseEvent &event)
{
    Destroy();
}

void LoginForm::OnQuit(wxCommandEvent &event)
{
    Destroy();
}

void LoginForm::OnAbout(wxCommandEvent &event)
{
    //wxMessageBox(_("Hello"));
}

void LoginForm::OnEditMouseEnter(wxMouseEvent &event)
{
	if(!_tcscmp(event.GetEventObject()->GetClassInfo()->GetClassName(),_T("wxTextCtrl")))
	{
		((wxTextCtrl*)(event.GetEventObject()))->SetFocus();
		((wxTextCtrl*)(event.GetEventObject()))->SetSelection(-1, -1);
		event.Skip();
	}
}

void LoginForm::OnLogin(wxCommandEvent& event)
{
    m_bLoginImmediately = true;
    Login();
}

void LoginForm::Login()
{
    wxBeginBusyCursor();
    if(!m_bLoginImmediately)
    {
        m_pStaictCountdown->SetLabel(wxString(_T("10")));
        sizerLogin->Show(sizerLoginMain, false);
        sizerLogin->Show(sizerLoginOpt, false);
        sizerLogin->Show(sizerLoginProcess, true);
        Layout();
        m_pTimer->Start(1000);
    }
    else
    {
        if(m_bEncodedPasswd && m_sEncodedPasswd.CompareTo(m_pEditLoginPasswd->GetValue())) m_bEncodedPasswd = false;
        if(m_pGoogleCalendar->auth(m_pEditLoginAccount->GetValue(),
                m_bEncodedPasswd ?
                (new Crypt())->dec(m_pEditLoginPasswd->GetValue()) :
                m_pEditLoginPasswd->GetValue()
            ))
        {
            wxFileConfig *config = new wxFileConfig(_T("GoogleCalendarClient"), _T(""), wxGetCwd() + _T("/config.dat"), _T(""), wxCONFIG_USE_LOCAL_FILE);
            wxConfigBase::Set(config);
            config->Write(_T("/login/rememberaccount"), m_pCbLoginOptRemAccount->GetValue());
            config->Write(_T("/login/account"), m_pCbLoginOptRemAccount->GetValue() ? m_pEditLoginAccount->GetValue() : _T(""));
            config->Write(_T("/login/rememberpassword"), m_pCbLoginOptRemPasswd->GetValue());
            config->Write(_T("/login/password"),
                m_pCbLoginOptRemPasswd->GetValue() ?
                    (m_bEncodedPasswd ? m_pEditLoginPasswd->GetValue() : (new Crypt())->enc(m_pEditLoginPasswd->GetValue()))
                    : _T(""));
            config->Write(_T("/login/autologin"), m_pCbLoginOptAutoLogin->GetValue());
            Close(true);
        }
    }
    wxEndBusyCursor();
}

void LoginForm::OnTimer(wxTimerEvent &event)
{
    long seconds;
    m_pStaictCountdown->GetLabel().ToLong(&seconds);
    if(seconds > 0)
    {
        seconds -= 1;
        m_pStaictCountdown->SetLabel(wxString::Format(_T("%d"), seconds));
    }
    else
    {
        m_pTimer->Stop();
        m_bLoginImmediately = true;
        Login();
    }
}
void LoginForm::OnConnectImmediately(wxCommandEvent &event)
{
    m_pStaictCountdown->SetLabel(wxString(_T("0")));
    event.Skip();
}
void LoginForm::OnStopConnecting(wxCommandEvent &event)
{
    sizerLogin->Show(sizerLoginMain, true);
    sizerLogin->Show(sizerLoginOpt, true);
    sizerLogin->Show(sizerLoginProcess, false);
    Layout();
    event.Skip();
}

